//登录注册的模块
import {reqGetCode,reqRegister,reqUserLogin,reqUserInfo,reqLogout} from "@/api";
import {setToken,removeToken} from '@/utils/token'
//登录与注册的模块
const state={
    code:"",
    token:localStorage.getItem('token'),
    userInfo:{},
};
const mutations={
    GETCODE(state,code){
        state.code=code;
    },
    USERLOGIN(state,token){
        state.token=token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo;
    },
    //清除本地数据
    CLEAR(state){
        state.token="";
        state.userInfo={};
        removeToken();
    }
};
const actions={
    //获取验证码
   async getCode({commit},phone){
        let result =await reqGetCode(phone)
        if (result.code==200){
            commit("GETCODE",result.data);
            return 'ok'
        }else {
            return Promise.reject(new Error('笑死，你真笨！'));
        }
    },
    //用户注册
   async uRegister({commit},user){
       let result =await reqRegister(user)
       if (result.code==200){
           return 'ok'
       }else {
           return Promise.reject(new Error('笑死，你真笨！'));
       }
       /*const {phone,code,password,password1}=this;
       (phone&&code&&password==password1) && this.$store.dispatch('uRegister',{phone,code,password});
 */   },
    //登录业务
   async userLogin({commit},data){
        let result =await reqUserLogin(data);
       if (result.code==200){
           commit("USERLOGIN",result.data.token);
           //持久化存储token
           setToken(result.data.token);
           return 'ok'
       }else {
           return Promise.reject(new Error('笑死，你真笨！'));
       }
   },
    //获取用户信息
    async getUserInfo({commit}){
       let result=await reqUserInfo();
       if (result.code==200){
           commit('GETUSERINFO',result.data);
           return 'ok'
       }else {
           return Promise.reject(new Error('笑死，你真笨！'));
       }
    },
    //退出登录
    async userLogout({commit}){
       //只是发请求通知服务器销毁当前token【学生证】
       let result=await reqLogout();
       if (result.code==200){
           commit("CLEAR");
       }
    }
};
const getters ={};
export default {
    state,
    mutations,
    actions,
    getters
}
